<template>
  <el-dialog v-model="importDlg"  title="导入接口" width="60%" :before-close="clickClear" custom-class="class_dialog" top="50px">
    <div>
      <el-check-tag v-for="(option, index) in options" :key="index" :class="{ 'selected': selectedOption === option.value }" @click="selectOption(option.value)" class="option">
        <i ><icon :icon="option.icon" class="importIcon"/></i>{{ option.label }}
      </el-check-tag>
    </div>
    <div v-if="selectedOption==='Postman'">
      <div class="help-box">
      支持导入 <el-tag>Postman</el-tag> 集合、环境、全局数据。
      <div class="curl-support-list">
        <p><strong>支持的格式：</strong></p>
        <ul>
          <li><el-tag size="small">Collection v2.0/v2.1</el-tag> Postman集合</li>
          <li><el-tag size="small">Environment</el-tag> Postman环境变量</li>
          <li><el-tag size="small">Globals</el-tag> Postman全局变量</li>
        </ul>
      </div>
      </div>
      <el-form :model="postmanForm" :rules="rulesPostman" ref="postmanRef">
        <el-form-item label="Postman文件" prop="file">
          <el-upload
            class="upload-demo"
            drag
            action="#"
            :auto-upload="false"
            :on-change="handlePostmanFileChange"
            :limit="1"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              拖拽文件到此处或 <em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                请上传Postman导出的JSON文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="节点/模块" prop="treenode">
          <el-cascader
            v-model="postmanForm.treenode"
            :options="treeOptions"
            :props="{label:'name', value:'id',checkStrictly: true}"
            @change="removeCascaderAriaOwns"
            @visible-change="removeCascaderAriaOwns"
            @expand-change="removeCascaderAriaOwns"
            clearable
            change-on-select
            filterable
            placeholder="请选择节点/模块"
          />
        </el-form-item>
      </el-form>
    </div>
    <div v-if="selectedOption==='Curl'">
      <div class="help-box">
        支持导入 <el-tag>Curl</el-tag> 命令，从外部复制后自动解析为接口内容。
        <div class="curl-support-list">
          <p><strong>支持的参数：</strong></p>
          <ul>
            <li><el-tag size="small">-X, --request</el-tag> 指定HTTP请求方法</li>
            <li><el-tag size="small">-H, --header</el-tag> 指定请求头</li>
            <li><el-tag size="small">-d, --data</el-tag> 指定请求体数据</li>
            <li><el-tag size="small">--data-binary</el-tag> 二进制数据</li>
            <li><el-tag size="small">--data-urlencode</el-tag> URL编码数据</li>
            <li><el-tag size="small">--data-raw</el-tag> 原始数据</li>
            <li><el-tag size="small">-F, --form</el-tag> 表单数据</li>
            <li><el-tag size="small">-A, --user-agent</el-tag> 用户代理</li>
            <li><el-tag size="small">-e, --referer</el-tag> 引用页</li>
            <li><el-tag size="small">-b, --cookie</el-tag> Cookie</li>
            <li><el-tag size="small">-u, --user</el-tag> 基本认证</li>
          </ul>
        </div>
      </div>
      <el-form :model="curlForm" :rules="rulesCurl" ref="curlRef">
        <el-form-item label="Curl命令" prop="curlContent">
          <el-input
            v-model="curlForm.curlContent"
            type="textarea"
            :rows="8"
            placeholder='请粘贴curl命令，例如：curl -X POST "https://api.example.com/v1/users" -H "Content-Type: application/json" -d {"name":"test"}'
            clearable
          />
        </el-form-item>
        <el-form-item label="节点/模块" prop="treenode">
          <el-cascader
            v-model="curlForm.treenode"
            :options="treeOptions"
            :props="{label:'name', value:'id',checkStrictly: true}"
            @change="removeCascaderAriaOwns"
            @visible-change="removeCascaderAriaOwns"
            @expand-change="removeCascaderAriaOwns"
            clearable
            change-on-select
            filterable
            placeholder="请选择节点/模块"
          />
        </el-form-item>
      </el-form>
    </div>
    <div v-if="selectedOption==='YApi'">
      <div class="help-box">
      支持手动、自动导入 <el-tag>YApi</el-tag> 平台的接口数据。
      </div>
      <div>
      <el-check-tag v-for="(optionYApi, index) in optionYApi"
                    :key="index"
                    :class="{ 'selectedYApi': selectedOptionYApi === optionYApi.value }"
                    @click="selectOptionYApi(optionYApi.value)"
                    class="optionYApi">
        {{ optionYApi.label }}
      </el-check-tag>
      </div>
      <div v-if="selectedOptionYApi===0">
          <el-form :inline="true" :model="formInline" class="demo-form-inline" :rules="rulesYApi" ref="YApiRef">
            <el-form-item label="平台地址" prop='url'>
              <el-input v-model="formInline.url" placeholder="请输入YApi平台项目地址" clearable />
            </el-form-item>
            <el-form-item label="平台TOKEN" prop='token'>
              <el-input v-model="formInline.token" placeholder="请输入YApi平台项目token" clearable />
            </el-form-item>
            <el-form-item label="平台项目ID" prop='YApiId'>
              <el-input v-model="formInline.YApiId" placeholder="请输入YApi平台项目id" clearable />
            </el-form-item>
            <el-form-item label="节点/模块" prop='treenode'>
              <el-cascader
                  v-model="formInline.treenode"
                  :options="treeOptions"
                  :props="{label:'name', value:'id',checkStrictly: true}"
                  @change="removeCascaderAriaOwns"
                  @visible-change="removeCascaderAriaOwns"
                  @expand-change="removeCascaderAriaOwns"
                  clearable
                  change-on-select
                  filterable
                  placeholder="请选择节点/模块"
                  />
            </el-form-item>
          </el-form>
      </div>
      <div v-else >
        <div class="help-warning">
          因与定时任务功能入口重复，请移至定时任务功能入口进行自动同步
        </div>
      </div>
    </div>
    <div v-if="selectedOption==='Apipost'">
      <div class="help-box">
        支持导入 <el-tag>Apipost</el-tag> 集合数据。
        <div class="curl-support-list">
          <p><strong>支持的格式：</strong></p>
          <ul>
            <li><el-tag size="small">Collection</el-tag> Apipost集合</li>
            <li><el-tag size="small">Environment</el-tag> Apipost环境变量</li>
          </ul>
        </div>
      </div>
      <el-form :model="apipostForm" :rules="rulesApipost" ref="apipostRef">
        <el-form-item label="Apipost文件" prop="file">
          <el-upload
            class="upload-demo"
            drag
            action="#"
            :auto-upload="false"
            :on-change="handleApipostFileChange"
            :limit="1"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              拖拽文件到此处或 <em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                请上传Apipost导出的JSON文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="节点/模块" prop="treenode">
          <el-cascader
            v-model="apipostForm.treenode"
            :options="treeOptions"
            :props="{label:'name', value:'id',checkStrictly: true}"
            @change="removeCascaderAriaOwns"
            @visible-change="removeCascaderAriaOwns"
            @expand-change="removeCascaderAriaOwns"
            clearable
            change-on-select
            filterable
            placeholder="请选择节点/模块"
          />
        </el-form-item>
      </el-form>
    </div>
    <div v-if="selectedOption==='Swagger'">
      <div class="help-box">
        支持导入 <el-tag>Swagger</el-tag> 接口文档。
        <div class="curl-support-list">
          <p><strong>支持的格式：</strong></p>
          <ul>
            <li><el-tag size="small">OpenAPI 2.0/3.0</el-tag> Swagger规范</li>
            <li><el-tag size="small">JSON/YAML</el-tag> 文件格式</li>
            <li><el-tag size="small">URL</el-tag> Swagger文档地址</li>
          </ul>
        </div>
      </div>
      <el-form :model="swaggerForm" :rules="rulesSwagger" ref="swaggerRef">
        <el-form-item label="导入方式">
          <el-radio-group v-model="swaggerForm.importType">
            <el-radio :label="'file'">文件导入</el-radio>
            <el-radio :label="'url'">URL导入</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <template v-if="swaggerForm.importType === 'file'">
          <el-form-item label="Swagger文件" prop="file">
            <el-upload
              class="upload-demo"
              drag
              action="#"
              :auto-upload="false"
              :on-change="handleSwaggerFileChange"
              :limit="1"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                拖拽文件到此处或 <em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  请上传Swagger JSON或YAML文件
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </template>
        
        <template v-else>
          <el-form-item label="Swagger URL" prop="url">
            <el-input 
              v-model="swaggerForm.url" 
              placeholder="请输入Swagger文档URL，例如：https://petstore.swagger.io/v2/swagger.json"
              clearable
            />
          </el-form-item>
        </template>
        
        <el-form-item label="节点/模块" prop="treenode">
          <el-cascader
            v-model="swaggerForm.treenode"
            :options="treeOptions"
            :props="{label:'name', value:'id',checkStrictly: true}"
            @change="removeCascaderAriaOwns"
            @visible-change="removeCascaderAriaOwns"
            @expand-change="removeCascaderAriaOwns"
            clearable
            change-on-select
            filterable
            placeholder="请选择节点/模块"
          />
        </el-form-item>
      </el-form>
    </div>
    <div v-if="selectedOption==='Js fetch'">
      <div class="help-box">
        支持导入 <el-tag>JS fetch</el-tag> 代码片段。
        <div class="curl-support-list">
          <p><strong>支持的格式：</strong></p>
          <ul>
            <li><el-tag size="small">fetch</el-tag> 原生fetch API</li>
            <li><el-tag size="small">axios</el-tag> axios请求</li>
            <li><el-tag size="small">jQuery</el-tag> $.ajax请求</li>
          </ul>
        </div>
      </div>
      <el-form :model="jsFetchForm" :rules="rulesJsFetch" ref="jsFetchRef">
        <el-form-item label="JS代码" prop="jsContent">
          <el-input
            v-model="jsFetchForm.jsContent"
            type="textarea"
            :rows="8"
            placeholder='请粘贴JS代码，例如：fetch("https://api.example.com/data", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "test" }) })'
            clearable
          />
        </el-form-item>
        <el-form-item label="节点/模块" prop="treenode">
          <el-cascader
            v-model="jsFetchForm.treenode"
            :options="treeOptions"
            :props="{label:'name', value:'id',checkStrictly: true}"
            @change="removeCascaderAriaOwns"
            @visible-change="removeCascaderAriaOwns"
            @expand-change="removeCascaderAriaOwns"
            clearable
            change-on-select
            filterable
            placeholder="请选择节点/模块"
          />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
        <span slot="footer" class="dialog-footer">
          <el-button @click="clickClear">取消</el-button>
          <el-button type="primary" :loading="isLoading" @click="importClick(selectedOption)">导入</el-button>
        </span>
    </template>
  </el-dialog>
</template>

<script>
import { Icon } from '@iconify/vue'
import {mapState} from "vuex";
import {ElMessage} from "element-plus";
import { Upload } from '@element-plus/icons-vue';

export default {
  components: {
   Icon,
   Upload
  },
  props: ['importDlg'],
  data() {
    return {
      isLoading: false,
      importDlg:this.importDlg,
      selectedOption: 'Postman', // 默认选中第一个选项
      selectedOptionYApi: 0, // 默认选中第一个选项
      rulesYApi: {
        url: [
					{
						required: true,
						message: '请输入YApi平台项目地址',
						trigger: 'blur'
					}
				],
				token: [
					{
						required: true,
						message: '请输入YApi平台项目token',
						trigger: 'blur'
					}
				],
				YApiId: [
					{
						required: true,
						message: '请输入YApi平台项目id',
						trigger: 'blur'
					}
				],
        treenode: [
					{
						required: true,
						message: '请选择节点/模块',
						trigger: 'blur'
					}
				]
			},
      rulesCurl: {
        curlContent: [
          {
            required: true,
            message: '请输入Curl命令',
            trigger: 'blur'
          }
        ],
        treenode: [
          {
            required: true,
            message: '请选择节点/模块',
            trigger: 'blur'
          }
        ]
      },
      rulesPostman: {
        file: [
          {
            required: true,
            message: '请选择Postman文件',
            trigger: 'change'
          }
        ],
        treenode: [
          {
            required: true,
            message: '请选择节点/模块',
            trigger: 'blur'
          }
        ]
      },
      rulesApipost: {
        file: [
          {
            required: true,
            message: '请选择Apipost文件',
            trigger: 'change'
          }
        ],
        treenode: [
          {
            required: true,
            message: '请选择节点/模块',
            trigger: 'blur'
          }
        ]
      },
      rulesSwagger: {
        file: [
          {
            required: true,
            message: '请选择Swagger文件',
            trigger: 'change'
          }
        ],
        url: [
          {
            required: true,
            message: '请输入Swagger文档URL',
            trigger: 'blur'
          }
        ],
        treenode: [
          {
            required: true,
            message: '请选择节点/模块',
            trigger: 'blur'
          }
        ]
      },
      rulesJsFetch: {
        jsContent: [
          {
            required: true,
            message: '请输入JS代码',
            trigger: 'blur'
          }
        ],
        treenode: [
          {
            required: true,
            message: '请选择节点/模块',
            trigger: 'blur'
          }
        ]
      },
      options: [
        { value: 'Postman', label: 'Postman', icon: 'devicon:postman' },
        { value: 'Apipost', label: 'Apipost', icon: 'logos:appcircle-icon'},
        { value: 'Curl', label: 'Curl', icon: 'logos:codio'},
        { value: 'Swagger', label: 'Swagger', icon: 'vscode-icons:file-type-swagger' },
        { value: 'Js fetch', label: 'Js fetch', icon: 'logos:nodejs-icon'},
        { value: 'YApi', label: 'YApi', icon: 'logos:yii' }
      ],
      optionYApi: [
        { value: 0, label: '手动同步'},
        { value: 1, label: '自动同步'}
      ],
      curlForm: {
        curlContent: '',
        treenode: '',
      },
      postmanForm: {
        file: null,
        treenode: '',
      },
      apipostForm: {
        file: null,
        treenode: '',
      },
      swaggerForm: {
        importType: 'file',
        file: null,
        url: '',
        treenode: '',
      },
      jsFetchForm: {
        jsContent: '',
        treenode: '',
      },
      fileList: [
        {
          name: 'food.jpeg',
          url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
        },
        {
          name: 'food2.jpeg',
          url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
        },
      ],
    formInline:{
        token:'069a46f10333f6923285d9d312c0c912f2db0286b99c3a8ae3544fca38eb1f54',
        YApiId:17139,
        treenode:'',
        format:'list',
        project:'',
        url:'http://api.doc.jiyou-tech.com'
    },
    treeOptions:[]
    }
  },
  computed: {
    ...mapState(['pro']),
  },
  methods:{
    closeModal() {
      this.$emit('close-modal');
    },
    // 点击取消
    clickClear(){
      this.closeModal()
    },

    importClick(selectedOption) {
      if (selectedOption==='YApi'){
          this.getYApiImport()
      } else if (selectedOption==='Curl') {
          this.getCurlImport()
      } else if (selectedOption==='Postman') {
          this.getPostmanImport()
      } else if (selectedOption==='Apipost') {
          this.getApipostImport()
      } else if (selectedOption==='Swagger') {
          this.getSwaggerImport()
      } else if (selectedOption==='Js fetch') {
          this.getJsFetchImport()
      } else {}
    },

    selectOption(option) {
      this.selectedOption = option; // 更新选中选项
    },
    selectOptionYApi(option) {
      this.selectedOptionYApi = option; // 更新选中选项
    },
    handleChange(uploadFile, uploadFiles) {
      this.fileList = this.fileList.slice(-3);
    },
    handlePostmanFileChange(file) {
      this.postmanForm.file = file.raw;
    },
    handleApipostFileChange(file) {
      this.apipostForm.file = file.raw;
    },
    handleSwaggerFileChange(file) {
      this.swaggerForm.file = file.raw;
    },

    // 解决el-cascader组件页面卡顿问题
    removeCascaderAriaOwns() {
      this.$nextTick(() => {
        const $el = document.querySelectorAll(
                '.el-cascader-panel .el-cascader-node[aria-owns]'
        );
        Array.from($el).map(item => item.removeAttribute('aria-owns'));
      });
    },

    // 解析curl命令
    parseCurlCommand(curlCommand) {
      // 基本结构
      let result = {
        method: 'POST',
        url: '',
        headers: {},
        data: null
      };
      
      // 提取请求方法
      const methodMatch = curlCommand.match(/-X\s+([A-Z]+)/i) || curlCommand.match(/--request\s+([A-Z]+)/i);
      if (methodMatch) {
        result.method = methodMatch[1].toUpperCase();
      }
      
      // 提取URL - 使用更可靠的方法
      let url = null;
      
      // 尝试从curl命令后直接提取URL
      const directUrlMatch = curlCommand.match(/curl\s+['"]([^'"]+)['"]/i);
      if (directUrlMatch) {
        url = directUrlMatch[1];
      } else {
        // 尝试从未加引号的URL提取
        const unquotedUrlMatch = curlCommand.match(/curl\s+(\S+)/i);
        if (unquotedUrlMatch) {
          url = unquotedUrlMatch[1];
        }
      }
      
      // 清理URL，移除可能的引号和特殊字符
      if (url) {
        result.url = url.replace(/^['"]|['"]$/g, '').replace(/\^/g, '');
      }
      
      // 提取请求头
      const headerMatches = [...curlCommand.matchAll(/-H\s+['"]([^:]+):\s*([^'"]+)['"]/gi), 
                            ...curlCommand.matchAll(/--header\s+['"]([^:]+):\s*([^'"]+)['"]/gi)];
      for (const match of headerMatches) {
        let headerName = match[1].trim();
        let headerValue = match[2].trim();
        
        // 清理headers中的特殊字符
        headerName = headerName.replace(/\^/g, '');
        headerValue = headerValue.replace(/\^/g, '').replace(/\\"/g, '"').replace(/\\'/g, "'");
        
        result.headers[headerName] = headerValue;
      }
      
      // 提取Cookie (-b/--cookie)
      const cookieMatches = [...curlCommand.matchAll(/-b\s+['"]([^'"]+)['"]/gi),
                            ...curlCommand.matchAll(/--cookie\s+['"]([^'"]+)['"]/gi)];
      for (const match of cookieMatches) {
        let cookieValue = match[1].trim();
        
        // 清理cookie中的特殊字符
        cookieValue = cookieValue.replace(/\^/g, '').replace(/\\"/g, '"').replace(/\\'/g, "'");
        
        result.headers['Cookie'] = cookieValue;
      }
      
      // 提取请求体 - 使用更可靠的方法
      
      // 查找--data-raw参数
      let dataRaw = this.extractQuotedValue(curlCommand, '--data-raw');
      if (dataRaw) {
        try {
          result.data = JSON.parse(dataRaw);
        } catch (e) {
          result.data = dataRaw;
        }
        return result;
      }
      
      // 查找-d或--data参数
      let data = this.extractQuotedValue(curlCommand, '-d') || 
                this.extractQuotedValue(curlCommand, '--data');
      if (data) {
        try {
          result.data = JSON.parse(data);
        } catch (e) {
          result.data = this.parseDataString(data);
        }
        return result;
      }
      
      // 查找--data-binary参数
      let dataBinary = this.extractQuotedValue(curlCommand, '--data-binary');
      if (dataBinary) {
        result.data = dataBinary;
        if (!result.headers['Content-Type']) {
          result.headers['Content-Type'] = 'application/octet-stream';
        }
        return result;
      }
      
      // 查找--data-urlencode参数
      let dataUrlEncode = this.extractQuotedValue(curlCommand, '--data-urlencode');
      if (dataUrlEncode) {
        result.data = this.parseDataString(dataUrlEncode);
        if (!result.headers['Content-Type']) {
          result.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        }
        return result;
      }
      
      // 处理表单数据 (-F/--form)
      const formMatches = [...curlCommand.matchAll(/-F\s+['"]([^=]+)=([^'"]*)['"]/gi),
                          ...curlCommand.matchAll(/--form\s+['"]([^=]+)=([^'"]*)['"]/gi)];
      if (formMatches.length > 0) {
        const formData = {};
        for (const match of formMatches) {
          formData[match[1].trim()] = match[2].trim();
        }
        result.data = formData;
        if (!result.headers['Content-Type']) {
          result.headers['Content-Type'] = 'multipart/form-data';
        }
      }
      
      // 处理用户代理 (--user-agent/-A)
      const userAgentMatch = curlCommand.match(/--user-agent\s+['"](.+?)['"]/i) ||
                            curlCommand.match(/-A\s+['"](.+?)['"]/i);
      if (userAgentMatch) {
        result.headers['User-Agent'] = userAgentMatch[1];
      }
      
      // 处理引用页 (--referer/-e)
      const refererMatch = curlCommand.match(/--referer\s+['"](.+?)['"]/i) ||
                          curlCommand.match(/-e\s+['"](.+?)['"]/i);
      if (refererMatch) {
        result.headers['Referer'] = refererMatch[1];
      }
      
      // 处理基本认证 (--user/-u)
      const authMatch = curlCommand.match(/--user\s+['"](.+?)['"]/i) ||
                        curlCommand.match(/-u\s+['"](.+?)['"]/i);
      if (authMatch) {
        const auth = authMatch[1];
        // 如果包含冒号，说明是用户名:密码格式
        if (auth.includes(':')) {
          const [username, password] = auth.split(':');
          // 创建Basic认证头
          const base64Auth = btoa(`${username}:${password}`);
          result.headers['Authorization'] = `Basic ${base64Auth}`;
        }
      }
      
      return result;
    },
    
    // 提取引号中的值，处理嵌套引号和转义字符
    extractQuotedValue(text, paramName) {
      // 查找参数后面的单引号或双引号内容
      const singleQuoteRegex = new RegExp(`${paramName}\\s+'([^']*(?:\\\\.[^']*)*)'+`, 'i');
      const doubleQuoteRegex = new RegExp(`${paramName}\\s+"([^"]*(?:\\\\.[^"]*)*)"`, 'i');
      
      // 尝试匹配单引号
      const singleMatch = text.match(singleQuoteRegex);
      if (singleMatch) return singleMatch[1];
      
      // 尝试匹配双引号
      const doubleMatch = text.match(doubleQuoteRegex);
      if (doubleMatch) return doubleMatch[1];
      
      // 如果上述方法都失败，尝试更复杂的方法
      // 找到参数的位置
      const paramPos = text.indexOf(paramName);
      if (paramPos === -1) return null;
      
      // 从参数位置开始查找第一个引号
      let startPos = text.indexOf("'", paramPos);
      if (startPos === -1) startPos = text.indexOf('"', paramPos);
      if (startPos === -1) return null;
      
      // 确定使用的是哪种引号
      const quoteChar = text[startPos];
      
      // 找到匹配的结束引号
      let endPos = startPos + 1;
      let escaped = false;
      
      while (endPos < text.length) {
        if (text[endPos] === '\\') {
          escaped = !escaped;
        } else if (text[endPos] === quoteChar && !escaped) {
          break;
        } else {
          escaped = false;
        }
        endPos++;
      }
      
      if (endPos >= text.length) return null;
      
      // 提取引号中的内容
      let extractedValue = text.substring(startPos + 1, endPos);
      
      // 清理提取的值，移除Windows命令行特有的字符
      extractedValue = extractedValue.replace(/\^/g, ''); // 移除^字符
      extractedValue = extractedValue.replace(/\\"/g, '"'); // 将\"转换为"
      extractedValue = extractedValue.replace(/\\'/g, "'"); // 将\'转换为'
      extractedValue = extractedValue.replace(/\\\\/g, '\\'); // 将\\转换为\
      
      return extractedValue;
    },
    
    // 辅助函数：解析数据字符串
    parseDataString(dataStr) {
      // 尝试解析为键值对格式 (key=value&key2=value2)
      if (dataStr.includes('=') && dataStr.match(/^[^=]+=.+/)) {
        const params = {};
        const pairs = dataStr.split('&');
        for (const pair of pairs) {
          const [key, value] = pair.split('=');
          if (key && value !== undefined) {
            params[decodeURIComponent(key)] = decodeURIComponent(value);
          }
        }
        return params;
      }
      // 否则返回原始字符串
      return dataStr;
    },

    // 解析JS fetch代码
    parseJsFetch(jsCode) {
      // 基本结构
      let result = {
        method: 'GET',
        url: '',
        headers: {},
        data: null
      };
      
      // 解析fetch API
      if (jsCode.includes('fetch(')) {
        // 提取URL
        const urlMatch = jsCode.match(/fetch\s*\(\s*["']([^"']+)["']/);
        if (urlMatch) {
          result.url = urlMatch[1];
        }
        
        // 提取method
        const methodMatch = jsCode.match(/method\s*:\s*["']([^"']+)["']/i);
        if (methodMatch) {
          result.method = methodMatch[1].toUpperCase();
        }
        
        // 提取headers
        const headersMatch = jsCode.match(/headers\s*:\s*(\{[^}]+\})/);
        if (headersMatch) {
          try {
            // 将字符串转换为可执行的JS对象表达式
            const headersStr = headersMatch[1].replace(/(['"])?([a-zA-Z0-9_]+)(['"])?\s*:/g, '"$2": ');
            // 使用eval解析headers对象（在受控环境中使用）
            const headers = eval(`(${headersStr})`);
            result.headers = headers;
          } catch (e) {
            console.error('解析headers失败:', e);
          }
        }
        
        // 提取body
        const bodyMatch = jsCode.match(/body\s*:\s*JSON\.stringify\s*\(([^)]+)\)/);
        if (bodyMatch) {
          try {
            // 将字符串转换为可执行的JS对象表达式
            const bodyStr = bodyMatch[1].replace(/(['"])?([a-zA-Z0-9_]+)(['"])?\s*:/g, '"$2": ');
            // 使用eval解析body对象（在受控环境中使用）
            result.data = eval(`(${bodyStr})`);
          } catch (e) {
            console.error('解析body失败:', e);
          }
        }
      }
      
      // 解析axios请求
      else if (jsCode.includes('axios(') || jsCode.includes('axios.')) {
        // 提取method
        const methodMatch = jsCode.match(/(?:axios|axios\.(get|post|put|delete|patch))\s*\(/i);
        if (methodMatch && methodMatch[1]) {
          result.method = methodMatch[1].toUpperCase();
        } else {
          const methodDefMatch = jsCode.match(/method\s*:\s*["']([^"']+)["']/i);
          if (methodDefMatch) {
            result.method = methodDefMatch[1].toUpperCase();
          }
        }
        
        // 提取URL
        const urlMatch = jsCode.match(/(?:axios|axios\.[a-z]+)\s*\(\s*["']([^"']+)["']/i) || 
                        jsCode.match(/url\s*:\s*["']([^"']+)["']/i);
        if (urlMatch) {
          result.url = urlMatch[1];
        }
        
        // 提取headers
        const headersMatch = jsCode.match(/headers\s*:\s*(\{[^}]+\})/);
        if (headersMatch) {
          try {
            const headersStr = headersMatch[1].replace(/(['"])?([a-zA-Z0-9_]+)(['"])?\s*:/g, '"$2": ');
            const headers = eval(`(${headersStr})`);
            result.headers = headers;
          } catch (e) {
            console.error('解析headers失败:', e);
          }
        }
        
        // 提取data
        const dataMatch = jsCode.match(/data\s*:\s*(\{[^}]+\})/);
        if (dataMatch) {
          try {
            const dataStr = dataMatch[1].replace(/(['"])?([a-zA-Z0-9_]+)(['"])?\s*:/g, '"$2": ');
            result.data = eval(`(${dataStr})`);
          } catch (e) {
            console.error('解析data失败:', e);
          }
        }
      }
      
      // 解析jQuery ajax请求
      else if (jsCode.includes('$.ajax') || jsCode.includes('jQuery.ajax')) {
        // 提取URL
        const urlMatch = jsCode.match(/url\s*:\s*["']([^"']+)["']/i);
        if (urlMatch) {
          result.url = urlMatch[1];
        }
        
        // 提取method
        const methodMatch = jsCode.match(/type\s*:\s*["']([^"']+)["']/i) || 
                           jsCode.match(/method\s*:\s*["']([^"']+)["']/i);
        if (methodMatch) {
          result.method = methodMatch[1].toUpperCase();
        }
        
        // 提取headers
        const headersMatch = jsCode.match(/headers\s*:\s*(\{[^}]+\})/);
        if (headersMatch) {
          try {
            const headersStr = headersMatch[1].replace(/(['"])?([a-zA-Z0-9_]+)(['"])?\s*:/g, '"$2": ');
            const headers = eval(`(${headersStr})`);
            result.headers = headers;
          } catch (e) {
            console.error('解析headers失败:', e);
          }
        }
        
        // 提取data
        const dataMatch = jsCode.match(/data\s*:\s*(\{[^}]+\})/);
        if (dataMatch) {
          try {
            const dataStr = dataMatch[1].replace(/(['"])?([a-zA-Z0-9_]+)(['"])?\s*:/g, '"$2": ');
            result.data = eval(`(${dataStr})`);
          } catch (e) {
            console.error('解析data失败:', e);
          }
        }
      }
      
      return result;
    },

    // Curl导入接口
    async getCurlImport() {
      this.$refs.curlRef.validate(async valid => {
        if (!valid) return;
        
        this.isLoading = true;
        try {
          // 解析curl命令
          const parsedCurl = this.parseCurlCommand(this.curlForm.curlContent);
          
          // 构建导入参数
          let params = {
            method: parsedCurl.method,
            url: parsedCurl.url,
            headers: parsedCurl.headers,
            body: parsedCurl.data || {},
            project: this.pro.id
          };
          
          // 处理节点/模块
          if (this.curlForm.treenode && this.curlForm.treenode.length > 0) {
            const lastValue = this.curlForm.treenode[this.curlForm.treenode.length - 1];
            params.treenode = lastValue;
          }
          
          // 调用API导入
          const response = await this.$api.getCurlImport(params);
          
          if (response.status === 201) {
            ElMessage({
              type: 'success',
              message: 'Curl导入成功',
              duration: 1000
            });
            this.closeModal();
          }
        } catch (error) {
          ElMessage({
            type: 'error',
            message: 'Curl解析失败，请检查格式是否正确',
            duration: 2000
          });
          console.error('Curl解析错误:', error);
        } finally {
          this.isLoading = false;
        }
      });
    },

    async getYApiImport(){
      this.$refs.YApiRef.validate(async vaild => {
        if (!vaild) return;
      this.isLoading = true;
      let params = { ...this.formInline};
			params.project = this.pro.id;
			// 获取最后一个节点的id
			if (params.treenode && params.treenode.length > 0) {
        const lastValue = params.treenode[params.treenode.length - 1];  // 获取最后一个值
        params.treenode = lastValue
      }
      const response = await this.$api.getYApiImport(params)
        if (response.status === 201) {
            ElMessage({
              type: 'success',
              message: '导入成功',
              duration: 1000
            });
            this.closeModal()
          }
			  this.isLoading = false;
      })
    },

    async getPostmanImport() {
      this.$refs.postmanRef.validate(async valid => {
        if (!valid) return;
        this.isLoading = true;
        try {
          const formData = new FormData();
          formData.append('file', this.postmanForm.file);
          formData.append('project', this.pro.id);

          if (this.postmanForm.treenode && this.postmanForm.treenode.length > 0) {
            const lastValue = this.postmanForm.treenode[this.postmanForm.treenode.length - 1];
            formData.append('treenode', lastValue);
          }

          const response = await this.$api.getPostmanImport(formData);

          if (response.status === 201) {
            ElMessage({
              type: 'success',
              message: 'Postman导入成功',
              duration: 1000
            });
            this.closeModal();
          }
        } catch (error) {
          ElMessage({
            type: 'error',
            message: 'Postman导入失败，请检查文件格式或网络',
            duration: 2000
          });
          console.error('Postman导入错误:', error);
        } finally {
          this.isLoading = false;
        }
      });
    },

    async getApipostImport() {
      this.$refs.apipostRef.validate(async valid => {
        if (!valid) return;
        this.isLoading = true;
        try {
          const formData = new FormData();
          formData.append('file', this.apipostForm.file);
          formData.append('project', this.pro.id);

          if (this.apipostForm.treenode && this.apipostForm.treenode.length > 0) {
            const lastValue = this.apipostForm.treenode[this.apipostForm.treenode.length - 1];
            formData.append('treenode', lastValue);
          }

          const response = await this.$api.getApipostImport(formData);

          if (response.status === 201) {
            ElMessage({
              type: 'success',
              message: 'Apipost导入成功',
              duration: 1000
            });
            this.closeModal();
          }
        } catch (error) {
          ElMessage({
            type: 'error',
            message: 'Apipost导入失败，请检查文件格式或网络',
            duration: 2000
          });
          console.error('Apipost导入错误:', error);
        } finally {
          this.isLoading = false;
        }
      });
    },

    async getSwaggerImport() {
      this.$refs.swaggerRef.validate(async valid => {
        if (!valid) return;
        this.isLoading = true;
        try {
          let params = {};
          if (this.swaggerForm.importType === 'file') {
            const formData = new FormData();
            formData.append('file', this.swaggerForm.file);
            formData.append('project', this.pro.id);
            if (this.swaggerForm.treenode && this.swaggerForm.treenode.length > 0) {
              const lastValue = this.swaggerForm.treenode[this.swaggerForm.treenode.length - 1];
              formData.append('treenode', lastValue);
            }
            params = formData;
          } else if (this.swaggerForm.importType === 'url') {
            params = {
              url: this.swaggerForm.url,
              project: this.pro.id,
              treenode: this.swaggerForm.treenode ? this.swaggerForm.treenode[this.swaggerForm.treenode.length - 1] : ''
            };
          }

          const response = await this.$api.getSwaggerImport(params);

          if (response.status === 201) {
            ElMessage({
              type: 'success',
              message: 'Swagger导入成功',
              duration: 1000
            });
            this.closeModal();
          }
        } catch (error) {
          ElMessage({
            type: 'error',
            message: 'Swagger导入失败，请检查文件格式或网络',
            duration: 2000
          });
          console.error('Swagger导入错误:', error);
        } finally {
          this.isLoading = false;
        }
      });
    },

    async getJsFetchImport() {
      this.$refs.jsFetchRef.validate(async valid => {
        if (!valid) return;
        this.isLoading = true;
        try {
          // 解析JS fetch代码
          const parsedJsFetch = this.parseJsFetch(this.jsFetchForm.jsContent);
          
          // 构建导入参数
          let params = {
            method: parsedJsFetch.method,
            url: parsedJsFetch.url,
            headers: parsedJsFetch.headers,
            body: parsedJsFetch.data || {},
            project: this.pro.id
          };
          
          // 处理节点/模块
          if (this.jsFetchForm.treenode && this.jsFetchForm.treenode.length > 0) {
            const lastValue = this.jsFetchForm.treenode[this.jsFetchForm.treenode.length - 1];
            params.treenode = lastValue;
          }
          
          const response = await this.$api.getJsFetchImport(params);

          if (response.status === 201) {
            ElMessage({
              type: 'success',
              message: 'JS fetch导入成功',
              duration: 1000
            });
            this.closeModal();
          }
        } catch (error) {
          ElMessage({
            type: 'error',
            message: 'JS fetch导入失败，请检查代码格式或网络',
            duration: 2000
          });
          console.error('JS fetch导入错误:', error);
        } finally {
          this.isLoading = false;
        }
      });
    },
    // 树结构列表接口
    async allTree() {
      const response = await this.$api.getTreeNode()
      if (response.status === 200) {
        this.treeOptions = response.data.result}
     },



  },
  created() {
    this.allTree()
  }

}
</script>

<style scoped>
.option {
  cursor: pointer;
  color: #000;
  margin:0px 0px 25px 15px;
  width: 150px;
  line-height: 30px;
  font-weight: 400;
}

.selected {
  background-color: #b2d8ff; /* 高亮展示的背景颜色 */
  color: white; /* 高亮展示时的字体颜色 */
}
.importIcon {
  margin-right: 8px;
  margin-left: -5px;
  font-size:25px;
  border-radius: 50%;
  display: inline-block; /* 将元素设置为行内块级元素 */
  vertical-align: middle; /* 垂直居中对齐 */

}

.help-box {
    background-color: #fafafb;
    padding: 20px;
    border-radius: 5px;
    margin:0 10px 20px 14px;
}
.help-warning {
    background-color: #fdf6ec;
    padding: 20px;
    border-radius: 5px;
    margin:0 10px 20px 14px;
}

.curl-support-list {
    margin-top: 15px;
    font-size: 14px;
}

.curl-support-list ul {
    display: flex;
    flex-wrap: wrap;
    padding-left: 0;
    list-style: none;
    margin-top: 10px;
}

.curl-support-list li {
    margin-right: 20px;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
}

.curl-support-list .el-tag {
    margin-right: 5px;
}

.dialog-footer {
  margin-top: 30px;
  margin-right: 10px;
}

.optionYApi {
  margin:0px 0px 25px 15px;
  cursor: pointer;
  color: #409eff;
  font-weight: 400;
}

.selectedYApi {
  background-color: #409eff; /* 高亮展示的背景颜色 */
  color: white; /* 高亮展示时的字体颜色 */
}
.el-upload-dragger {
  background-color: #fff;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  box-sizing: border-box;
  width: 100%;
  height: auto;
  min-height: 120px;
  max-height: 180px;
  text-align: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.upload-demo {
  width: 100%;
  max-width: 100%;
}
.el-form-item .el-upload-dragger {
  width: 100%;
  box-sizing: border-box;
}

/* 添加响应式样式 */
@media screen and (max-width: 768px) {
  .el-upload-dragger {
    min-height: 100px;
    max-height: 120px;
  }
  
  .el-upload__text {
    font-size: 14px;
  }
  
  .el-upload__tip {
    font-size: 12px;
  }
}

/* 确保上传组件不会溢出容器 */
:deep(.el-upload) {
  width: 100%;
}

:deep(.el-upload-dragger) {
  width: 100%;
}
</style>